import axios from 'axios';

let util = {};

util.ajax = axios.create({
  // baseURL: ajaxUrl,
  timeout: 30000,
  headers: { 'Content-type': 'application/json', 'Accept': 'application/json' },
  // withCredentials: true
});

util.getStorageSync = function (key) {
  let storage = localStorage.getItem(key)
  return JSON.parse(storage)
}

util.getStorage = function (key) {
  let storage = localStorage.getItem(key)
  return JSON.parse(storage)
}

util.setStorage = function (data) {
  localStorage.setItem(data.key, JSON.stringify(data.data))
}
util.setStorageSync = function (key, data) {
  localStorage.setItem(key, JSON.stringify(data))
}

util.navigateTo = function (url, query) {
  this.$router.push({ path: url, query: query })
}

util.removeStorageSync = function (key) {
  localStorage.removeItem(key)
}

util.cookie = {
  set: function (name, value) {
    // 缓存过期时间
    let Days = 30
    let exp = new Date()
    exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000)
    document.cookie = name + '=' + escape(value) + ';expires=' + exp.toGMTString() + ';path=/'
  },
  get: function (name) {
    let arr = new RegExp('(^| )' + name + '=([^;]*)(;|$)')
    let reg = arr
    arr = document.cookie.match(reg)
    if (arr) {
      return unescape(arr[2])
    } else {
      return null
    }
  },
  del: function (name) {
    let exp = new Date()
    exp.setTime(exp.getTime() - 1)
    let cval = this.cookie.get(name)
    if (cval != null) {
      document.cookie = name + '=' + cval + ';expires=' + exp.toGMTString() + ';path=/'
    }
  }
}
util.tranferAddress = function (address) {
  let addr = []
  address.forEach(n => {
    addr.push({
      name: n.name,
      tel: n.phone,
      province: n.province,
      city: n.city,
      county: n.area,
      area_code: n.area_code,
      address: n.province + n.city + n.area + n.address,
      id: n.id,
      is_default: n.is_default == 1 ? true : false
    })
  })

  return addr
},

util.getToken = function () {
  let app_se = util.getStorageSync('app_select') || {}
  // console.log(121, app_se);
  return app_se.aid || ''
  // return util.getCookieSync('token') || Config.token
}

util.ajax.interceptors.request.use(
  config => {
    config.headers.Authorization = window.sessionStorage.getItem('token')
    return config
  },
  err => {
    return Promise.reject(err)
  }
);

//拦截器
axios.interceptors.response.use(
  response => {
    return response
  },
  error => {
    console.log(error, 'error response')
    if (error.response) {
      switch (error.response.status) {
        case 401:
          // 返回 401 清除token信息并跳转到登录页面
          confirm('过期')
          router.replace({
            path: '/login'
          })
          location.reload()
      }
    }
    return Promise.reject(error.response.data)   // 返回接口返回的错误信息
  })

util.hasClass = function (el, name) {
  if (el.className.split(' ').indexOf(name) == -1) {
    return false
  } else {
    return true
  }
}

export default util;
